
// character_attribute_panel/frontend/js/script.js
document.addEventListener('DOMContentLoaded', function() {
  // 全局变量
  const characterData = {
    mainAttribute: 85,
    attributes: {},
    history: []
  };

  // 初始化
  initializeAttributes();
  initializeCharts();
  setupEventListeners();
  initParticles();

  /**
   * 初始化所有属性
   */
  function initializeAttributes() {
    // 获取所有属性项
    const attributeItems = document.querySelectorAll('.attribute-item');
    attributeItems.forEach(item => {
      const attributeId = item.dataset.attribute;
      if (attributeId) {
        const valueElement = item.querySelector('.attribute-value');
        if (valueElement) {
          const value = parseInt(valueElement.textContent);
          characterData.attributes[attributeId] = value;
        }
      }
    });
    
    // 保存初始状态到历史记录
    saveToHistory('初始化');
  }

  /**
   * 初始化图表
   */
  function initializeCharts() {
    // 组织力曲线图表已在HTML中初始化
    updateOrganizationChart();
  }

  /**
   * 设置事件监听器
   */
  function setupEventListeners() {
    // 导入按钮
    document.getElementById('importBtn').addEventListener('click', () => {
      document.getElementById('importModal').classList.remove('hidden');
    });

    // 取消导入
    document.getElementById('cancelImport').addEventListener('click', () => {
      document.getElementById('importModal').classList.add('hidden');
    });

    // 确认导入
    document.getElementById('confirmImport').addEventListener('click', () => {
      importCharacterData();
    });

    // 导出按钮
    document.getElementById('exportBtn').addEventListener('click', () => {
      exportCharacterData();
    });

    // 添加属性按钮
    document.getElementById('addAttributeBtn').addEventListener('click', () => {
      document.getElementById('addAttributeModal').classList.remove('hidden');
    });

    // 取消添加属性
    document.getElementById('cancelAddAttribute').addEventListener('click', () => {
      document.getElementById('addAttributeModal').classList.add('hidden');
    });

    // 确认添加属性
    document.getElementById('confirmAddAttribute').addEventListener('click', () => {
      addCustomAttribute();
    });

    // 修复HTML中的导入按钮点击事件
    document.getElementById('importBtn').addEventListener('click', () => {
      document.getElementById('importModal').classList.remove('hidden');
    });
  }

  /**
   * 初始化粒子效果
   */
  function initParticles() {
    // 粒子效果已在HTML中初始化
  }

  /**
   * 调整属性值
   * @param {string} attributeId - 属性ID
   * @param {number} change - 变化值
   */
  window.adjustAttribute = function(attributeId, change) {
    let targetElement, bar;
    
    if (attributeId === 'mainAttribute') {
      targetElement = document.getElementById('mainAttributeValue');
      bar = document.getElementById('mainAttributeBar');
      let currentValue = characterData.mainAttribute;
      currentValue = Math.max(0, Math.min(100, currentValue + change));
      characterData.mainAttribute = currentValue;
      targetElement.textContent = currentValue;
      bar.style.width = `${currentValue}%`;
      
      // 视觉反馈
      applyAttributeChangeEffect(targetElement, change);
      
      // 更新依赖于主属性的其他属性
      updateDependentAttributes('mainAttribute', change);
      
    } else {
      const attributeItems = document.querySelectorAll('.attribute-item');
      for (const item of attributeItems) {
        if (item.dataset.attribute === attributeId) {
          targetElement = item.querySelector('.attribute-value');
          bar = item.querySelector('.attribute-bar');
          
          let currentValue = characterData.attributes[attributeId] || parseInt(targetElement.textContent);
          currentValue = Math.max(0, Math.min(100, currentValue + change));
          characterData.attributes[attributeId] = currentValue;
          
          targetElement.textContent = currentValue;
          bar.style.width = `${currentValue}%`;
          
          // 视觉反馈
          applyAttributeChangeEffect(targetElement, change);
          
          // 更新依赖于该属性的其他属性
          updateDependentAttributes(attributeId, change);
          
          break;
        }
      }
    }
    
    // 更新主属性的计算
    recalculateMainAttribute();
    
    // 更新图表
    updateOrganizationChart();
    
    // 保存到历史记录
    saveToHistory(`调整${attributeId} ${change > 0 ? '+' : ''}${change}`);
  };

  /**
   * 应用属性变化的视觉效果
   * @param {HTMLElement} element - 目标元素
   * @param {number} change - 变化值
   */
  function applyAttributeChangeEffect(element, change) {
    element.classList.remove('increase', 'decrease');
    
    if (change > 0) {
      element.classList.add('increase');
    } else if (change < 0) {
      element.classList.add('decrease');
    }
    
    setTimeout(() => {
      element.classList.remove('increase', 'decrease');
    }, 600);
  }

  /**
   * 更新依赖于特定属性的其他属性
   * @param {string} attributeId - 属性ID
   * @param {number} change - 变化值
   */
  function updateDependentAttributes(attributeId, change) {
    // 定义属性之间的关联关系
    const dependencies = {
      // 才智系统
      'intelligence': ['decision', 'judgment'],
      'talent': ['fame', 'reputation'],
      'capability': ['execution', 'leadership', 'organization'],
      
      // 权威系统
      'authority': ['leadership', 'leadership2', 'organization', 'organization2', 'organization3'],
      'legal': ['decision'],
      'identity': ['reputation'],
      'charm': ['affinity', 'communication'],
      
      // 声誉系统
      'reputation': ['fame'],
      'virtue': ['self-respect', 'self-love', 'self-peace'],
      'fame': ['charm'],
      
      // 沟通系统
      'affinity': ['communication'],
      'communication': ['execution'],
      'execution': ['organization', 'organization2', 'organization3'],
      
      // 领导系统
      'inspiration': ['leadership', 'leadership2'],
      'guidance': ['judgment'],
      'leadership': ['decision', 'organization', 'organization2', 'organization3'],
      
      // 决策系统
      'decision': ['leadership2', 'judgment'],
      'judgment': ['decision'],
      
      // 善念善行系统
      'self-respect': ['self-confidence'],
      'self-peace': ['self-reliance'],
      'self-love': ['self-strengthening'],
      'self-confidence': ['charm', 'leadership'],
      'self-reliance': ['execution'],
      'self-strengthening': ['capability']
    };
    
    // 如果有定义依赖关系
    if (dependencies[attributeId]) {
      // 影响系数 - 变化的一小部分会影响关联属性
      const impactFactor = 0.25;
      const impactChange = Math.floor(change * impactFactor);
      
      if (impactChange !== 0) {
        dependencies[attributeId].forEach(dependentId => {
          // 调用adjustAttribute但不触��依赖更新，避免循环
          updateAttributeDirectly(dependentId, impactChange);
        });
      }
    }
  }

  /**
   * 直接更新属性值，不触发依赖更新
   * @param {string} attributeId - 属性ID
   * @param {number} change - 变化值
   */
  function updateAttributeDirectly(attributeId, change) {
    if (attributeId === 'mainAttribute') {
      let targetElement = document.getElementById('mainAttributeValue');
      let bar = document.getElementById('mainAttributeBar');
      let currentValue = characterData.mainAttribute;
      currentValue = Math.max(0, Math.min(100, currentValue + change));
      characterData.mainAttribute = currentValue;
      targetElement.textContent = currentValue;
      bar.style.width = `${currentValue}%`;
      
      // 视觉反馈
      applyAttributeChangeEffect(targetElement, change);
    } else {
      const attributeItems = document.querySelectorAll('.attribute-item');
      for (const item of attributeItems) {
        if (item.dataset.attribute === attributeId) {
          let targetElement = item.querySelector('.attribute-value');
          let bar = item.querySelector('.attribute-bar');
          
          let currentValue = characterData.attributes[attributeId] || parseInt(targetElement.textContent);
          currentValue = Math.max(0, Math.min(100, currentValue + change));
          characterData.attributes[attributeId] = currentValue;
          
          targetElement.textContent = currentValue;
          bar.style.width = `${currentValue}%`;
          
          // 视觉反馈
          applyAttributeChangeEffect(targetElement, change);
          
          break;
        }
      }
    }
  }

  /**
   * 重新计算主属性值
   */
  function recalculateMainAttribute() {
    // 根据子属性计算主属性值
    // 才智系统贡献40%
    const intelligenceSystem = calculateSystemAverage(['intelligence', 'talent', 'ability', 'capability']);
    
    // 权威系统贡献30%
    const authoritySystem = calculateSystemAverage(['authority', 'legal', 'identity', 'charm']);
    
    // 声誉系统贡献30%
    const reputationSystem = calculateSystemAverage(['reputation', 'virtue', 'ability2', 'fame']);
    
    // 计算加权平均值
    const newMainValue = Math.round(
      intelligenceSystem * 0.4 +
      authoritySystem * 0.3 +
      reputationSystem * 0.3
    );
    
    // 更新主属性显示
    const mainElement = document.getElementById('mainAttributeValue');
    const mainBar = document.getElementById('mainAttributeBar');
    
    // 只有当值变化时才更新
    if (newMainValue !== characterData.mainAttribute) {
      const oldValue = characterData.mainAttribute;
      characterData.mainAttribute = newMainValue;
      mainElement.textContent = newMainValue;
      mainBar.style.width = `${newMainValue}%`;
      
      // 视觉反馈
      if (newMainValue > oldValue) {
        applyAttributeChangeEffect(mainElement, 1);
      } else if (newMainValue < oldValue) {
        applyAttributeChangeEffect(mainElement, -1);
      }
    }
  }

  /**
   * 计算一个系统中属性的平均值
   * @param {Array<string>} attributeIds - 属性ID数组
   * @returns {number} - 平均值
   */
  function calculateSystemAverage(attributeIds) {
    let sum = 0;
    let count = 0;
    
    attributeIds.forEach(id => {
      if (characterData.attributes[id] !== undefined) {
        sum += characterData.attributes[id];
        count++;
      }
    });
    
    return count > 0 ? Math.round(sum / count) : 0;
  }

  /**
   * 更新组织力曲线图表
   */
  function updateOrganizationChart() {
    // 获取Chart.js实例
    const chartInstance = Chart.getChart('orgChartCanvas');
    if (!chartInstance) return;
    
    // 从属性中获取最新数据
    // 这里使用了相关属性的平均值来计算每个维度
    const organizationData = [
      calculateAttribute(['decision', 'judgment'], 0.5), // 规划
      calculateAttribute(['communication', 'affinity'], 0.5), // 协调
      calculateAttribute(['execution'], 1), // 执行
      calculateAttribute(['authority', 'legal'], 0.5), // 控制
      calculateAttribute(['talent', 'ability', 'capability'], 0.33), // 创新
      calculateAttribute(['guidance', 'inspiration'], 0.5), // 培养
      calculateAttribute(['judgment', 'fame', 'reputation'], 0.33) // 评估
    ];
    
    // 更新图表数据
    chartInstance.data.datasets[0].data = organizationData;
    chartInstance.update();
  }

  /**
   * 计算属性组合
   * @param {Array<string>} attributes - 属性ID数组
   * @param {number} weight - 每个属性的权重
   * @returns {number} - 计算结果
   */
  function calculateAttribute(attributes, weight) {
    let sum = 0;
    attributes.forEach(attr => {
      if (characterData.attributes[attr] !== undefined) {
        sum += characterData.attributes[attr] * weight;
      }
    });
    return Math.round(sum);
  }

  /**
   * 导出角色数据
   */
  function exportCharacterData() {
    const exportData = {
      name: "角色配置",
      mainAttribute: characterData.mainAttribute,
      attributes: characterData.attributes,
      timestamp: new Date().toISOString(),
      version: "1.0"
    };
    
    //建临时文本区域用于复制
    const textArea = document.createElement('textarea');
    textArea.value = JSON.stringify(exportData, null, 2);
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    
    // 通知用户
    showToast('数据已复制到剪贴板');
    
    // 下载文件
    const blob = new Blob([JSON.stringify(exportData, null, 2)], {type: 'application/json'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `character-attributes-${new Date().toISOString().slice(0, 10)}.json`;
    document.body.appendChild(a);
    a.click();
    setTimeout(() => {
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }, 0);
  }

  /**
   * 导入角色数据
   */
  function importCharacterData() {
    const importText = document.getElementById('importData').value.trim();
    if (!importText) {
      showToast('请输入有效的角色数据', 'error');
      return;
    }
    
    try {
      const importData = JSON.parse(importText);
      
      // 验证数据格式
      if (!importData.attributes || typeof importData.mainAttribute !== 'number') {
        throw new Error('数据格式无效');
      }
      
      // 更新主属性
      characterData.mainAttribute = importData.mainAttribute;
      document.getElementById('mainAttributeValue').textContent = importData.mainAttribute;
      document.getElementById('mainAttributeBar').style.width = `${importData.mainAttribute}%`;
      
      // 更新其他属性
      for (const [attrId, value] of Object.entries(importData.attributes)) {
        characterData.attributes[attrId] = value;
        
        // 更新UI
        const attributeItems = document.querySelectorAll(`.attribute-item[data-attribute="${attrId}"]`);
        attributeItems.forEach(item => {
          const valueElem = item.querySelector('.attribute-value');
          const barElem = item.querySelector('.attribute-bar');
          if (valueElem && barElem) {
            valueElem.textContent = value;
            barElem.style.width = `${value}%`;
          }
        });
      }
      
      // 关闭导入模态框
      document.getElementById('importModal').classList.add('hidden');
      document.getElementById('importData').value = '';
      
      // 更新图表
      updateOrganizationChart();
      
      // 保存到历史记录
      saveToHistory('导入数据');
      
      showToast('数据导入成功');
    } catch (error) {
      showToast('数据格式错误，请检查JSON格式', 'error');
      console.error('导入错误:', error);
    }
  }

  /**
   * 添加自定义属性
   */
  function addCustomAttribute() {
    const name = document.getElementById('attributeName').value.trim();
    const category = document.getElementById('attributeCategory').value;
    const value = parseInt(document.getElementById('attributeValue').value);
    
    if (!name) {
      showToast('请输入属性名称', 'error');
      return;
    }
    
    if (isNaN(value) || value < 0 || value > 100) {
      showToast('请输入0-100之间的属性值', 'error');
      return;
    }
    
    // 生成唯一ID
    const attributeId = `custom-${Date.now()}`;
    
    // 创建新的属性项
    const newAttributeItem = createAttributeItem(name, attributeId, value);
    
    // 添加到对应的类别中
    let targetCategory;
    switch (category) {
      case 'intelligence':
        targetCategory = document.querySelector('.attribute-category:nth-child(1)');
        break;
      case 'authority':
        targetCategory = document.querySelector('.attribute-category:nth-child(2)');
        break;
      case 'reputation':
        targetCategory = document.querySelector('.attribute-category:nth-child(3)');
        break;
      case 'communication':
        targetCategory = document.querySelector('.panel:nth-child(1)');
        break;
      case 'leadership':
        targetCategory = document.querySelector('.panel:nth-child(2)');
        break;
      case 'decision':
        targetCategory = document.querySelector('.panel:nth-child(3)');
        break;
      case 'virtue':
        targetCategory = document.querySelector('.panel:nth-child(4) .grid');
        break;
      default:
        targetCategory = document.querySelector('.attribute-category:nth-child(1)');
    }
    
    // 找到目标容器
    const container = targetCategory ? targetCategory.querySelector('.grid') : null;
    
    if (container) {
      container.appendChild(newAttributeItem);
      
      // 保存到数据中
      characterData.attributes[attributeId] = value;
      
      // 应用动画效果
      newAttributeItem.classList.add('fade-in');
      
      // 关闭模态框
      document.getElementById('addAttributeModal').classList.add('hidden');
      document.getElementById('attributeName').value = '';
      document.getElementById('attributeValue').value = '50';
      
      // 为新属性设置事件处理
      const increaseBtn = newAttributeItem.querySelector('.p-1.bg-blue-600');
      const decreaseBtn = newAttributeItem.querySelector('.p-1.bg-red-600');
      
      if (increaseBtn) {
        increaseBtn.onclick = () => adjustAttribute(attributeId, 1);
      }
      
      if (decreaseBtn) {
        decreaseBtn.onclick = () => adjustAttribute(attributeId, -1);
      }
      
      // 保存到历史记录
      saveToHistory(`添加属性: ${name}`);
      
      showToast('属性添加成功');
    } else {
      showToast('无法找到目标分类', 'error');
    }
  }

  /**
   * 创建属性项元素
   * @param {string} name - 属性名称
   * @param {string} id - 属性ID
   * @param {number} value - 属性值
   * @returns {HTMLElement} - 创建的元素
   */
  function createAttributeItem(name, id, value) {
    const div = document.createElement('div');
    div.className = 'attribute-item p-3';
    div.dataset.attribute = id;
    
    div.innerHTML = `
      <div class="flex justify-between items-center mb-2">
        <span class="font-medium">${name}</span>
        <span class="attribute-value">${value}</span>
      </div>
      <div class="bg-gray-700 h-2 rounded-full overflow-hidden">
        <div class="attribute-bar" style="width: ${value}%;"></div>
      </div>
      <div class="mt-2 flex justify-end">
        <button class="p-1 bg-blue-600 hover:bg-blue-500 rounded mr-1">
          <i class="fas fa-plus text-xs"></i>
        </button>
        <button class="p-1 bg-red-600 hover:bg-red-500 rounded">
          <i class="fas fa-minus text-xs"></i>
        </button>
      </div>
    `;
    
    return div;
  }

  /**
   * 保存当前状态到历史记录
   * @param {string} description - 历史记录描述
   */
  function saveToHistory(description) {
    characterData.history.push({
      timestamp: new Date().toISOString(),
      mainAttribute: characterData.mainAttribute,
      attributes: { ...characterData.attributes },
      description: description
    });
    
    // 限制历史记录长度
    if (characterData.history.length > 50) {
      characterData.history.shift();
    }
  }

  /**
   * 显示toast消息
   * @param {string} message - 消息内容
   * @param {string} type - 消息类型 (success, error)
   */
  function showToast(message, type = 'success') {
    // 检查是否已存在toast，如果有则移除
    const existingToast = document.querySelector('.toast');
    if (existingToast) {
      document.body.removeChild(existingToast);
    }
    
    // 创建新的toast
    const toast = document.createElement('div');
    toast.className = `fixed bottom-4 right-4 z-50 px-4 py-2 rounded-lg shadow-lg toast ${
      type === 'error' ? 'bg-red-500' : 'bg-green-500'
    }`;
    toast.textContent = message;
    
    // 添加到body
    document.body.appendChild(toast);
    
    // 应用动画
    setTimeout(() => {
      toast.style.opacity = '1';
      toast.style.transform = 'translateY(0)';
    }, 10);
    
    // 自动消失
    setTimeout(() => {
      toast.style.opacity = '0';
      toast.style.transform = 'translateY(10px)';
      
      setTimeout(() => {
        if (document.body.contains(toast)) {
          document.body.removeChild(toast);
        }
      }, 300);
    }, 3000);
  }
});
